(ns tala.db
  (:require [clojure.java.jdbc :as sql]))

;; For some useful JDBC examples, see
;; http://en.wikibooks.org/wiki/Clojure_Programming/Examples/JDBC_Examples

(defn list-user-tables [db]
  (sql/with-connection db
    (sql/with-query-results rs ["select * from sys.objects where type = 'U'"]
      (doseq [row rs] (println (:name row)))))
  (sql/with-connection db
    (into []
          (sql/resultset-seq
           (-> (sql/connection)
               (.getMetaData)
               (.getTables "AstroDAbis" "dbo" nil (into-array ["TABLE"]))
               ;(.getTables nil nil nil (into-array ["TABLE" "VIEW"]))
               )))))

(defn make-query [db q f]
  "Make a query: db is a database map, q a vector containing strings, and f a function which is applied to the result sequence"
  (sql/with-connection db
    (sql/with-query-results rs q
      (f rs))))

(defn print-query [db q]
  (sql/with-connection db
    (sql/with-query-results rs [q]
      (let [ks (keys (first rs))]
        (println ks)
        (doseq [row rs]
          (doseq [k ks]
            (print (row k) "\t"))
          (println))))))

;; Call with 'lein run -m tala.db [args...]'
;; (defn -main [& args]
;;   (println "Hello there!: " args)
;;   (if args
;;     (print-query (first args))
;;     (list-user-tables)))

